import requests
from typing import List
from django.core.files.uploadedfile import UploadedFile
from io import BytesIO
from PIL import Image
class NSFWChecker:
    def __init__(self):
        self.api_url = "http://localhost:3000/classify-many"
        self.threshold = 0.6

    def check_images(self, images: List[UploadedFile]) -> bool:
        try:
            # 准备文件上传
            files = []
            for image in images:
                print(f"[DEBUG] 文件名: {image.name}")
                print(f"[DEBUG] 文件类型: {image.content_type}")
                print(f"[DEBUG] 文件大小: {image.size} bytes")
                
                 # 转换WebP到PNG
                if image.content_type == 'image/webp':
                    img = Image.open(image)
                    img.verify()  # 验证图片完整性
                    output = BytesIO()
                    img.save(output, format='PNG')
                    output.seek(0)
                    file_content = output.read()
                    files.append(('images', ('converted.png', file_content)))
                else:
                    file_content = image.read()
                    files.append(('images', (image.name, file_content)))
                image.seek(0)
                print(f"[DEBUG] 请求头: {requests.post(self.api_url).headers}")         
            # 添加超时设置和详细的错误处理
            response = requests.post(
                self.api_url, 
                files=files,
                timeout=10,
            )
            
            print(f"[DEBUG] 响应状态码: {response.status_code}")
            print(f"[DEBUG] 响应头: {response.headers}")
            print(f"[DEBUG] 响应内容: {response.text}")
            
            response.raise_for_status()
            results = response.json()
            
            # 检查每张图片的分类结果
            for idx, result in enumerate(results):
                print(f"[DEBUG] 图片 {idx+1} 的分类结果:")
                print(f"porn: {result.get('porn', 0):.4f}")
                print(f"hentai: {result.get('hentai', 0):.4f}")
                print(f"sexy: {result.get('sexy', 0):.4f}")
                print(f"neutral: {result.get('neutral', 0):.4f}")
                print(f"drawing: {result.get('drawing', 0):.4f}")
                
                if (result.get('porn', 0) > self.threshold or 
                    result.get('hentai', 0) > self.threshold or 
                    result.get('sexy', 0) > self.threshold):
                    raise ValueError("图片包含不适当内容")

            print("[DEBUG] 所有图片通过审核")
            return True

        except requests.RequestException as e:
            print(f"[ERROR] API 请求失败:")
            print(f"[ERROR] 异常类型: {type(e).__name__}")
            print(f"[ERROR] 异常信息: {str(e)}")
            if hasattr(e.response, 'text'):
                print(f"[ERROR] 服务器响应: {e.response.text}")
            raise ValueError(f"图片审核服务异常: {str(e)}")
            
        except Exception as e:
            print(f"[ERROR] 图片审核失败: {type(e).__name__} - {str(e)}")
            raise ValueError(f"图片审核失败: {str(e)}")